package com.design.twords.adatper;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import com.design.twords.R;
import com.design.twords.activity.WordListActivity;
import com.design.twords.config.ConfigData;
import com.design.twords.config.ConstantValue;
import com.design.twords.database.BookList;
import com.design.twords.database.Phrase_all;
import com.design.twords.database.Phrase_learn;
import com.design.twords.database.RelWord_all;
import com.design.twords.database.RelWord_learn;
import com.design.twords.database.Sentence_all;
import com.design.twords.database.Sentence_learn;
import com.design.twords.database.Translation_all;
import com.design.twords.database.Translation_learn;
import com.design.twords.database.UserConfig;
import com.design.twords.database.Word_all;
import com.design.twords.database.Word_learn;
import com.design.twords.entity.ItemWordBook;
import com.design.twords.json.JsonForDatabase;
import com.design.twords.utils.FileUtil;

import org.litepal.LitePal;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Create by Alen
 * Time:  15:17
 */
public class WordBookAdapter extends RecyclerView.Adapter<WordBookAdapter.MyViewHolder> {

    public interface ItemClickListener{
        void itemLongClickListener(int position);
    }

    private static final String TAG = "WordBookAdapter";

    private LayoutInflater myinflater;

    private ArrayList<ItemWordBook> wordBooks;
    private Context context;

    private ItemClickListener listener;
    private ProgressDialog progressDialog;

    private static final int FINISH = 1;
    private static final int DOWN_DONE = 2;
    private static final int FAIL = 3;

    //子View Id
    private int viewId;

    private android.os.Handler handler = new android.os.Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case FINISH:
                    progressDialog.setMessage("解析完成");

                    Bundle bundle = msg.getData();
                    Intent intent =new Intent(context, WordListActivity.class);
                    intent.putExtra("floder_id",bundle.getInt("floder_id"));
                    intent.putExtra("sources", "wordbooklist");
                    context.startActivity(intent);
                    progressDialog.dismiss();
                    break;
                case DOWN_DONE:
                    progressDialog.setMessage("已下载完成，正在解压分析数据中...");
                    break;
                case FAIL:
                    progressDialog.setMessage("解析出错,请重试");
                    progressDialog.setCancelable(true);
                    break;


            }
        }
    };

    public WordBookAdapter(Context cont,  ArrayList<ItemWordBook> wordBooks, int viewId) {
        this.context = cont;
        this.myinflater = LayoutInflater.from(cont);
        this.wordBooks = wordBooks;
        this.viewId = viewId;

    }

    public void setWordBooks(ArrayList<ItemWordBook> wordBooks) {
        this.wordBooks = wordBooks;
    }

    //设置监听器
    public void setListener(ItemClickListener listener) {
        this.listener = listener;
    }


    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
       return new MyViewHolder(myinflater.inflate(viewId, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        ItemWordBook item = wordBooks.get(position);
        holder.imageView.setImageResource(item.getBookImg());
        holder.bookName.setText(item.getBookName());
        holder.bookRes.setText(item.getBookSource());
        holder.bookCounts.setText(item.getBookWordNum()+"");


        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i(TAG, "position:"+item.getBookName());
                openBookEvent(item);
            }
        });
        holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    if(listener != null){
                        listener.itemLongClickListener(position);
                    }
                    return true;
                }
        });

    }

    private void openBookEvent(ItemWordBook item) {
        if(item.isHasdown()){
            //已经下载的打开单词本
            Intent intent =new Intent(context, WordListActivity.class);
            intent.putExtra("floder_id",item.getBookId());
            intent.putExtra("sources", "wordbooklist");
            context.startActivity(intent);

        }else {
            //没有下载的点击后选择是否下载
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setTitle("提示")
                    .setMessage("是否下载该书籍")
                    .setNegativeButton("取消",null)
                    .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                           progressDialog = new ProgressDialog(context);
                           progressDialog.setTitle("请稍等");
                           progressDialog.setMessage("数据正在下载...");
                           progressDialog.setCancelable(false);
                           progressDialog.show();
                           new Handler().postDelayed(new Runnable() {
                               @Override
                               public void run() {
                                   Thread thread = new Thread(new Runnable() {
                                       @Override
                                       public void run() {
                                           try {
                                               OkHttpClient client = new OkHttpClient();
                                               Request  request = new Request.Builder()
                                                       .url(ConstantValue.bookDownLoadAddressById(item.getBookId()))
                                                       .build();
                                               Response response = client.newCall(request).execute();
                                               Message message = new Message();
                                               message.what = DOWN_DONE;
                                               handler.sendMessage(message);
                                               //将文件下载到本地
                                               FileUtil.BytesToFile(response.body().bytes(),context.getFilesDir() + "/" + ConstantValue.DIR_TOTAL,
                                                       ConstantValue.bookFileNameById(item.getBookId()));
                                               //解压文件
                                               FileUtil.unZipFile(context.getFilesDir() + "/" + ConstantValue.DIR_TOTAL + "/" + ConstantValue.bookFileNameById(item.getBookId()),
                                                       context.getFilesDir() + "/" + ConstantValue.DIR_TOTAL + "/" + ConstantValue.DIR_AFTER_FINISH,false);

                                           } catch (Exception e) {
                                               e.printStackTrace();
                                           }
                                           //从本地加载json 文件 解析后存入到数据库中
                                           boolean flag = JsonForDatabase.analyseJson(FileUtil.readLocalJson(context.getFilesDir() + "/" + ConstantValue.DIR_TOTAL + "/"
                                                   + ConstantValue.DIR_AFTER_FINISH + "/" +ConstantValue.bookFileNameById(item.getBookId()).replace(".zip",".json")),
                                                   ConstantValue.getTypeById(item.getBookId()));
                                           if(flag){
                                               //将书籍信息存入到 Booklist 表中
                                               BookList book = new BookList();
                                               book.setBookId(item.getBookId());
                                               book.setBookname(item.getBookName());
                                               book.setWordcounts(item.getBookWordNum());
                                               long time = new Date().getTime();
                                               SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd  HH:mm");
                                               book.setCreatetime(sdf.format(time));
                                               book.save();

                                               Log.i(TAG, book.toString());
                                               Log.i(TAG, "书籍下载成功, 即将跳转到单词列表");

                                               //跳转到单词列表
                                               Bundle bundle = new Bundle();

                                               bundle.putInt("floder_id", item.getBookId());
                                               Message message = new Message();
                                               message.what = FINISH;
                                               message.setData(bundle);
                                               handler.sendMessage(message);
                                           }
                                           else{
                                               Message message = new Message();
                                               message.what = FAIL;
                                               handler.sendMessage(message);
                                           }

                                       }
                                   });
                                   thread.start();
                               }
                           },500);
                        }
                    }).show();
        }
    }


    @Override
    public int getItemCount() {
        return wordBooks.size();
    }

    public void deleteItem(int position) {
        ItemWordBook itemWordBook = wordBooks.get(position);
        String type = ConstantValue.getTypeById(itemWordBook.getBookId());


        int bookList_before = LitePal.count(BookList.class);
        Log.i(TAG, "booksize" + bookList_before);
        //如果当前书籍为正在使用的书籍 同时删除计划 和使用的数据
        List<UserConfig> all = LitePal.where("userId = ?", ConfigData.getUserId()).find(UserConfig.class);


        if(itemWordBook.getBookId() == all.get(0).getCurrentBookId()){
            LitePal.deleteAll(UserConfig.class,"userId = ?", ConfigData.getUserId());

            LitePal.beginTransaction();
            try{
                LitePal.deleteAll(Word_learn.class);
                LitePal.deleteAll(Translation_learn.class);
                LitePal.deleteAll(Sentence_learn.class);
                LitePal.deleteAll(RelWord_learn.class);
                LitePal.deleteAll(Phrase_learn.class);
                LitePal.setTransactionSuccessful();
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                LitePal.endTransaction();
            }
        }

        LitePal.beginTransaction();
        try{
            LitePal.deleteAll(BookList.class, "bookid = ?", itemWordBook.getBookId()+"");
            LitePal.deleteAll(Word_all.class, "wordBook = ?", type);
            LitePal.deleteAll(Translation_all.class, "wordBook = ?", type);
            LitePal.deleteAll(RelWord_all.class, "wordBook = ?", type);
            LitePal.deleteAll(Phrase_all.class, "wordBook = ?", type);
            LitePal.deleteAll(Sentence_all.class, "wordBook = ?", type);
            wordBooks.remove(position);
            LitePal.setTransactionSuccessful();

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            LitePal.endTransaction();
            notifyDataSetChanged();
        }
        int bookList_last = LitePal.count(BookList.class);
        Log.i(TAG, "booksize" + bookList_last);


    }

    public class MyViewHolder extends RecyclerView.ViewHolder {
        private ImageView imageView;
        private TextView bookName;
        private TextView bookRes;
        private TextView bookCounts;
        private CheckBox booklist_checkbox;
        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            imageView = (ImageView)itemView.findViewById(R.id.book_pic);
            bookName = itemView.findViewById(R.id.book_name);
            bookRes = itemView.findViewById(R.id.book_res);
            bookCounts = itemView.findViewById(R.id.book_wordcounts);
            booklist_checkbox = itemView.findViewById(R.id.booklist_checkbox);
        }
    }
}
